//
//  MusicWorksViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/8/19.
//

import UIKit
import JXSegmentedView
class MusicWorksViewController: BaseViewController, JXSegmentedListContainerViewListDelegate {
    var viewModel = MusicViewModel()
    var dataSource:[MusicModel] = []
    var disposeBag = DisposeBag()
     let releaseViewModel = WorksViewModel()
    var name:String = ""
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.register(cellWithClass: MusicWorksHistoryCell.self)
        view.rowHeight = UITableView.automaticDimension
        view.sectionHeaderHeight = 0
        view.estimatedSectionHeaderHeight = 0
        view.sectionFooterHeight = 0
        view.estimatedSectionFooterHeight = 0
        view.contentInsetAdjustmentBehavior = .never
        view.separatorStyle = .none
        view.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64 + bottomSafeAreaHeight, right: 0)
        view.emptyDataSetSource = self
        view.emptyDataSetDelegate = self
        return view
    }()
    private lazy var descGenerateBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "发布"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.titleColorForNormal = .white
        button.allRound(27)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.isHidden = true
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        self.view.addSubview(tableView)
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        }
        
        self.tableView.addHeaderRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page = 1
            self.tableView.reloadData()
            self.viewModel.userList()
        }
        
        self.tableView.addFooterRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page += 1
            self.viewModel.userList()
        }
        
        self.viewModel.userList()
        
        self.viewModel.reloadUserListDataSubject.subscribe(onNext: { [weak self] models in
            guard let self = self else { return }
            self.tableView.endFooterRefresh()
            self.tableView.endHeaderRefresh()
            if self.viewModel.page == 1 {
                self.dataSource = models
            }else {
                self.dataSource += models
            }
            self.tableView.reloadData()
        }).disposed(by: disposeBag)
        
        self.view.addSubview(descGenerateBtn)
        descGenerateBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-10)
            make.leading.trailing.equalToSuperview().inset(32)
            make.height.equalTo(54)
        }
        descGenerateBtn.setClosureTouchUpInside_k { [weak self] in
            self?.generate()
        }
        
        releaseViewModel.reloadListSubject.subscribe(onNext: { [weak self] in
            self?.reload()
            let vc = ReleaseViewController()
            vc.type = 1
            self?.navigationController?.pushViewController(vc)
        }).disposed(by: disposeBag)
        
        
        releaseViewModel.errorSubject.subscribe(onNext: { [weak self] in
            self?.reload()
            let vc = ReleaseViewController()
            vc.type = 2
            self?.navigationController?.pushViewController(vc)
        }).disposed(by: disposeBag)

    }
    func reload(){
        self.descGenerateBtn.isHidden = true
        for (index, value) in self.dataSource.enumerated() {
            self.dataSource[index].isSelect = false
        }
        self.tableView.reloadData()
    }
    func generate(){
        if let model = self.dataSource.first(where: { $0.isSelect == true } ) {
            self.releaseViewModel.releaseWorks(id: "\(model.id ?? 0)", type: 3)
        }else {
            NDProgressHUD.show(message: "请选择作品，在尝试发布。")
        }
    }
    
    func listView() -> UIView {
        return self.view
    }
}
extension MusicWorksViewController: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    // sts 状态：1生成中；2生成成功；3生成失败
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.dataSource[indexPath.item]
        let cell = tableView.dequeueReusableCell(withClass: MusicWorksHistoryCell.self)
        cell.setup(model: model)
        cell.stateIV.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            if model.sts == 2 {
                let vc = MusicPlayerDetailsViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            }
        }
        cell.selectIV.isHidden = !model.isSelect
        if model.isSelect {
            cell.backView.layer.borderWidth = 2
            cell.backView.layer.borderColor = UIColor(hexString: "#45DFFF").cgColor
        }else {
            cell.backView.layer.borderColor = UIColor.clear.cgColor
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 76
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.item]
        if model.sts == 2 {
            for (index, value) in self.dataSource.enumerated() {
                self.dataSource[index].isSelect = false
            }
            if model.isSelect {
                self.dataSource[indexPath.item].isSelect = false
            }else {
                self.dataSource[indexPath.item].isSelect = true
            }
            self.tableView.reloadData()
            checkState()
        }
    }
    func checkState(){
        if let model = self.dataSource.first(where: { $0.isSelect == true } ) {
            descGenerateBtn.isHidden = false
        }else {
            descGenerateBtn.isHidden = true
        }
    }
}
extension MusicWorksViewController: DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {
    open func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        UIImage(named: "icon_nodata")
    }
    
    open func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let text = "暂无数据，快去生成吧～"
        let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.pingFangSCRegular(ofSize: 15), .foregroundColor: Theme.color.text_d3]
        return NSAttributedString(string: text, attributes: attributes)
    }
    
}

class MusicWorksHistoryCell: UITableViewCell {
   
    lazy var backView: UIView = {
       let view = UIView()
        view.backgroundColor = UIColor.white
        view.allRound(8)
        return view
    }()
    
    lazy var coverIV: UIImageView = {
       let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = false
        imageView.image = UIImage(named: "icon_music_def")
        imageView.allRound(8)
        return imageView
    }()
    
    lazy var stateIV: UIButton = {
       let button = UIButton()
        button.imageForNormal = UIImage(named: "icon_music_player")
        return button
    }()
    
    lazy var titleLb: UILabel = {
       let label = UILabel()
        label.text = "我的女朋友白雪(My Dragon Lady)"
        label.textColor = Theme.color.text_d1
        label.font = UIFont.pingFangSCRegular(ofSize: 14)
        return label
    }()
    
    lazy var descLb: UILabel = {
       let label = UILabel()
        label.text = "2024-06-03 19:34:12"
        label.textColor = Theme.color.text_d3
        label.font = UIFont.pingFangSCRegular(ofSize: 11)
        return label
    }()
    
    lazy var selectIV: UIImageView = {
       let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_musicworks_sel")
        return imageView
    }()
     
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.addSubview(backView)
        backView.addSubviews([coverIV, stateIV, titleLb, descLb, selectIV])
        backView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.leading.trailing.equalToSuperview().inset(14)
            make.height.equalTo(68)
        }
        
        coverIV.snp.makeConstraints { make in
            make.top.leading.bottom.equalToSuperview().inset(10)
            make.width.equalTo(coverIV.snp.height)
        }
        
        stateIV.snp.makeConstraints { make in
            make.centerY.centerX.equalTo(coverIV)
        }
        
        titleLb.snp.makeConstraints { make in
            make.top.equalTo(coverIV.snp.top).offset(8)
            make.leading.equalTo(coverIV.snp.trailing).offset(8)
        }
        
        descLb.snp.makeConstraints { make in
            make.bottom.equalTo(coverIV.snp.bottom).offset(-8)
            make.leading.equalTo(coverIV.snp.trailing).offset(8)
        }
        
        selectIV.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-15)
            make.width.height.equalTo(24)
        }
    }
    
    
    func setup(model:MusicModel){

        if model.sts == 1 {
            self.coverIV.image = UIImage(named: "icon_music_def")
            self.stateIV.imageForNormal = UIImage(named: "icon_music_generate")
            self.titleLb.text = "生成中..."
            self.titleLb.textColor =  Theme.color.text_d3
        }else if model.sts == 2 {
            self.coverIV.sd_setImage(with: URL(string: model.cover_url))
            self.stateIV.imageForNormal = UIImage(named: "icon_music_player")
            self.titleLb.text = model.music_name ?? ""
            self.titleLb.textColor =  Theme.color.text_d1
        }else if model.sts == 3 {
            self.coverIV.image = UIImage(named: "icon_music_def")
            self.titleLb.text = "生成失败"
            self.titleLb.textColor = UIColor(hexString: "#FF2727")
            self.stateIV.imageForNormal = UIImage(named: "icon_music_error")
        }
        self.descLb.text = model.create_time
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
